import React, { useState, useRef } from "react";
import { Button, Modal, Space, message } from "antd";
import { useRequest } from 'ahooks';
import { PlusOutlined } from '@ant-design/icons';
import { ProColumnType, ProTable } from "@ant-design/pro-components";
import { warehouseTypes  } from "@/constants/types";
import { fetchDomesticWhList, addDomesticWh, updateDomesticWh, delDomesticWh, enableDomesticWh, disableDomesticWh } from "../services";
import WarehouseUpdateModal from "../modals/WarehouseUpdateModal";
import { calculateTableWidth } from "@/utils/util";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";

const Warehouse = () => {
  const tableRef = useRef();
  const [visible, setVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<warehouseTypes | null>(null);
  const {loading: addLoading, runAsync: addApi} = useRequest(addDomesticWh, {manual: true});
  const {loading: updateLoading, runAsync: updateApi} = useRequest(updateDomesticWh, {manual: true});


  const warehouseUpdateProps = {
    title: currentRow ? '修改仓库信息' : '新增仓库',
    visible,
    loading: addLoading || updateLoading,
    currentRow,
    onSubmit: async (params: warehouseTypes) => {
      const apiFunc = currentRow ? updateApi : addApi;
      const res = await apiFunc(currentRow ? {
        ...params, 
        id: currentRow?.id
      } : params);
      if (res.code === '0') {
        message.success('操作成功');
        setVisible(false);
        setCurrentRow(null);
        tableRef?.current?.reload();
      }
    },
    onCancel: () => {
      setVisible(false);
      setCurrentRow(null);
    }
  }

  const handleAdd = () => {
    setVisible(true);
  }
  const handleEdit = (record: warehouseTypes) => {
    setCurrentRow(record);
    setVisible(true);
  }
  // 删除
  const handleDel = (record: warehouseTypes) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定删除？',
      onOk: () => {
        delDomesticWh({id: record.id}).then(res => {
          tableRef?.current?.reload();
        })
      }
    });
  }
  // 启用
  const handleEnable = (record: warehouseTypes) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定启用仓库？',
      onOk: () => {
        enableDomesticWh({id: record.id}).then(res => {
          tableRef?.current?.reload();
        })
      }
    });
  }
  // 禁用
  const handleDisable = (record: warehouseTypes) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定禁用仓库？',
      onOk: () => {
        disableDomesticWh({id: record.id}).then(res => {
          tableRef?.current?.reload();
        })
      }
    });
  }

  const columns: ProColumnType<warehouseTypes> [] = [
    {
      title: '类型',
      search: false,
      width: 100,
      dataIndex: 'type',
      render: (_, record: warehouseTypes) => <XlTableDictColumn type="warehouseType" value={record?.type} />
    },
    {
      title: '使用状态',
      search: false,
      width: 100,
      dataIndex: 'status',
      render: (_, record: warehouseTypes) => <XlTableDictColumn type="warehouseStatus" value={record?.status} />
    },
    {
      title: '仓库代码',
      search: false,
      width: 100,
      dataIndex: 'code'
    },
    {
      title: '仓库名称',
      search: false,
      width: 150,
      ellipsis: true,
      dataIndex: 'name'
    },
    {
      title: '地址',
      search: false,
      width: 200,
      ellipsis: true,
      dataIndex: 'address',
      render: (_, record) => <span>{[record?.province, record?.city, record?.area, record?.address].filter(v => !!v).join('')}</span>
    },
    {
      title: '联系人',
      search: false,
      width: 100,
      dataIndex: 'contacts'
    },
    {
      title: '联系电话',
      search: false,
      width: 120,
      dataIndex: 'tel'
    },
    {
      title: '营业时间',
      search: false,
      width: 120,
      dataIndex: 'bussinessTime',
      render: (_, record) => {
        return (
          <span>{record?.openingTime} - {record?.closingTime}</span>
        );
      }
    },
    {
      title: '备注',
      search: false,
      width: 150,
      ellipsis: true,
      dataIndex: 'remark'
    },
    {
      title: '创建时间',
      search: false,
      width: 150,
      ellipsis: true,
      dataIndex: 'createTime'
    },
    {
      title: '操作',
      dataIndex: 'options',
      search: false,
      width: 250,
      ellipsis: true,
      fixed: 'right',
      render: (_, record: warehouseTypes) => {
        return (
          <Space>
            <Button onClick={() => handleEdit(record)} type="link">编辑</Button>
            <Button onClick={() => handleDel(record)} type="link">删除</Button>
            {String(record?.status) === '0' && <Button onClick={() => handleDisable(record)} type="link">禁用</Button>}
            {String(record?.status) === '1' && <Button onClick={() => handleEnable(record)} type="link">启用</Button>}
          </Space>
        );
      }
    }
  ];

  return (
    <> 
      <ProTable
        actionRef={tableRef}
        bordered
        rowKey="id"
        search={false}
        options={false}
        columns={columns}
        scroll={{x: calculateTableWidth(columns)}}
        request={async (params = {}, sort, filter) => {
          console.log(sort, filter);
          params.pageNum = params.current;
          const res = await fetchDomesticWhList({
            ...params,
            pageNum: params.current || 1,
            pageSize: params.pageSize || 20,
          });
          return {
            data: res.data || [],
            total: res.total || 0,
            success: true
          }
        }}
        pagination={{
          pageSize: 10
        }}
        toolBarRender={() => [
          <Button key="create" onClick={handleAdd} type="primary">
            <PlusOutlined />
            新建
          </Button>
        ]}
      />
      {visible && <WarehouseUpdateModal {...warehouseUpdateProps} />}
    </>
  );
};


export default Warehouse;